package cn.janus.config;

import cn.janus.pojo.entity.Bill;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {
    @Bean
    public RedisTemplate<String, Bill> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Bill> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        // 设置 key 的序列化方式
        template.setKeySerializer(new StringRedisSerializer());
        // 配置 Jackson2JsonRedisSerializer 以支持 LocalDate 类型
        Jackson2JsonRedisSerializer<Bill> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Bill.class);
        ObjectMapper om = new ObjectMapper();
        om.registerModule(new JavaTimeModule()); // 注册 JavaTimeModule 以支持 LocalDate
        jackson2JsonRedisSerializer.setObjectMapper(om);
        // 设置 value 的序列化方式
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置 hash 的 key 的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        // 设置 hash 的 value 的序列化方式
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        template.afterPropertiesSet();
        return template;
    }
}